package com.zhr.tea.view.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.zhr.tea.R;
import com.zhr.tea.entity.CarBean;
import com.zhr.tea.entity.CarGoodsBean;
import com.zhr.tea.utils.IsLogin;
import com.zhr.tea.view.activity.RegestActivity;
import com.zhr.tea.view.adapter.CarAdapter;
import com.zhr.tea.view.adapter.ShopCarAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static com.zhr.tea.api.CarService.CAR_SHOP_DEL_URL;
import static com.zhr.tea.api.CarService.CAR_SHOP_URL;
import static com.zhr.tea.api.CarService.CAR_URL;


/**
 * A simple {@link Fragment} subclass.
 */
public class CarFragment extends Fragment implements View.OnClickListener, ShopCarAdapter.PriceChange {

    @BindView(R.id.rv_car)
    RecyclerView rvCar;
    @BindView(R.id.rv_car_goods)
    RecyclerView rvGoods;
    @BindView(R.id.car_shop_before)
    SwipeRefreshLayout carShopBefore;
    @BindView(R.id.car_pay)
    Button carPay;
    @BindView(R.id.car_price)
    TextView carPrice;
    @BindView(R.id.car_shop_after)
    RelativeLayout carShopAfter;
    @BindView(R.id.car_selector_all)
    CheckBox carSelectorAll;
    @BindView(R.id.car_top_editor)
    TextView carTopEditor;
    @BindView(R.id.car_rv_price)
    RelativeLayout carRvPrice;

    private CarAdapter adapter;
    private List<CarBean.ContentBean> data;

    private ShopCarAdapter goodsAdapter;
    private List<CarGoodsBean.ContentBean> goods;

    public CarFragment() {
        // Required empty public constructor
    }

    public static CarFragment newInstance() {

        Bundle args = new Bundle();

        CarFragment fragment = new CarFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_car, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        ButterKnife.bind(this, view);
        data = new ArrayList<>();
        adapter = new CarAdapter(getContext(), data, new CarAdapter.ILogin() {
            @Override
            public void Login() {
                startActivity(new Intent(getActivity(), RegestActivity.class));
            }
        });
        RecyclerView.LayoutManager manager = new GridLayoutManager(getContext(), 2);
        rvCar.setLayoutManager(manager);
        rvCar.setAdapter(adapter);
        goods = new ArrayList<>();
        goodsAdapter = new ShopCarAdapter(getContext(), goods, this);

        LinearLayoutManager llManager = new LinearLayoutManager(getContext());
        rvGoods.setLayoutManager(llManager);
        rvGoods.setAdapter(goodsAdapter);

        //下拉刷新，查看购物车里的商品信息
        carShopBefore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (IsLogin.isLogin) {
                    getCar();
                }
                carShopBefore.setRefreshing(false);
            }
        });
        carSelectorAll.setOnClickListener(this);
        carPay.setOnClickListener(this);
        carTopEditor.setOnClickListener(this);
    }

    public void getCar() {//请求购物车里的商品
        RequestParams params = new RequestParams();
        params.addHeader("Content-Type", "application/json");
        JSONObject obj = new JSONObject();
        obj.put("phoneNum", IsLogin.user.getBody().getMemberAccount());
        params.applicationJson(obj);
        HttpRequest.post(CAR_SHOP_URL, params, new BaseHttpRequestCallback<CarGoodsBean>() {
            @Override
            protected void onSuccess(CarGoodsBean carGoodsBean) {
                super.onSuccess(carGoodsBean);
                goods.addAll(carGoodsBean.getContent());
                if (goods.size() != 0) {
                    carShopBefore.setVisibility(View.GONE);
                    carShopAfter.setVisibility(View.VISIBLE);
                } else {
                    carShopBefore.setVisibility(View.VISIBLE);
                    carShopAfter.setVisibility(View.GONE);
                }
                goodsAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initData() {
        RequestParams params = new RequestParams();
        params.addHeader("Content-Type", "application/json");
        JSONObject obj = new JSONObject();
        obj.put("beginId", "0");
        obj.put("loadSize", 20);
        obj.put("typeIds", "");
        obj.put("goodsIds", "");

        params.applicationJson(obj);
        HttpRequest.post(CAR_URL, params, new BaseHttpRequestCallback<CarBean>() {
            @Override
            protected void onSuccess(CarBean carBean) {
                super.onSuccess(carBean);
                data.addAll(carBean.getContent());
                adapter.notifyDataSetChanged();
            }
        });
    }

    //回到fragment，刷新适配器
    @Override
    public void onStart() {
        super.onStart();
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.car_selector_all:
                selectorAll();
                break;
            case R.id.car_pay:
                pay();
                break;
            case R.id.car_top_editor://编辑or完成
                editor();
                break;
        }
    }

    private void pay() {
        if (carTopEditor.getText().toString().equals("编辑")) {

        } else {
            StringBuffer typeIds = new StringBuffer("");
            StringBuffer goodsIds = new StringBuffer("");
            for (int i = goods.size() - 1; i >= 0; i--) {//删除选中的goods
                for (int j = goods.get(i).getGoodsList().size() - 1; j >= 0; j--) {
                    if (!goods.get(i).getGoodsList().get(j).isCheckedI()) {
                        typeIds.append(goods.get(i).getGoodsList().get(j).getTypeId() + ",");
                        goodsIds.append(goods.get(i).getGoodsList().get(j).getGoodsId() + ",");
                    } else {
                        goods.get(i).getGoodsList().remove(j);
                    }
                }
                if (goods.get(i).getGoodsList().size() == 0) {
                    goods.remove(i);
                }
            }
            String s1 = typeIds.substring(0, typeIds.length() - 1);
            String s2 = goodsIds.substring(0, goodsIds.length() - 1);
            //向服务器发送新的购物车商品id
            RequestParams params = new RequestParams();
            params.addHeader("Content-Type", "application/json");
            JSONObject obj = new JSONObject();
            obj.put("beginId", "0");
            obj.put("typeIds", s1);
            obj.put("loadSize", 20);
            obj.put("goodsIds", s2);
            params.applicationJson(obj);
            HttpRequest.post(CAR_SHOP_DEL_URL, params, new BaseHttpRequestCallback<CarGoodsBean>() {
                @Override
                protected void onSuccess(CarGoodsBean carGoodsBean) {
                    super.onSuccess(carGoodsBean);
//                    goods.clear();不清空了
                    if (carGoodsBean.getContent().size() != 0) {
//                        goods.addAll(carGoodsBean.getContent());
                    } else {
                        carShopBefore.setVisibility(View.VISIBLE);
                        carShopAfter.setVisibility(View.GONE);
                    }
                    goodsAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int errorCode, String msg) {
                    super.onFailure(errorCode, msg);
                    goods.clear();
                    goodsAdapter.notifyDataSetChanged();
                    carShopBefore.setVisibility(View.VISIBLE);
                    carShopAfter.setVisibility(View.GONE);
                }
            });
        }
    }

    private void editor() {
        if (carTopEditor.getText().toString().equals("编辑")) {
            carTopEditor.setText("完成");
            carPay.setText("删除");
            carPay.setBackgroundColor(Color.parseColor("#ff0000"));
            carRvPrice.setVisibility(View.GONE);
        } else {
            carTopEditor.setText("编辑");
            carPay.setText("去结算");
            carPay.setBackgroundColor(Color.parseColor("#cc26f523"));
            carRvPrice.setVisibility(View.VISIBLE);
        }
    }

    private void selectorAll() {
        for (int i = 0; i < goods.size(); i++) {
            goods.get(i).setCheckedG(carSelectorAll.isChecked());
            for (int j = 0; j < goods.get(i).getGoodsList().size(); j++) {
                goods.get(i).getGoodsList().get(j).setCheckedI(carSelectorAll.isChecked());
            }
        }
        goodsAdapter.notifyDataSetChanged();
        setPrice();
    }

    private void setPrice() {
        double price = 0.00;
        for (int i = 0; i < goods.size(); i++) {
            for (int j = 0; j < goods.get(i).getGoodsList().size(); j++) {
                if (goods.get(i).getGoodsList().get(j).isCheckedI()) {
                    price += Double.valueOf(goods.get(i).getGoodsList().get(j).getGoodsPrice()) * Integer.valueOf(goods.get(i).getGoodsList().get(j).getBuyCount());
                }
            }
        }
        carPrice.setText("合计" + price);
    }

    @Override
    public void change() {
        setPrice();
    }
}
